package control

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func SetRouter(r *gin.Engine)  {
	r.POST("/upload", Upload)
	r.POST("/login", Login)
	r.POST("/register", Register)
	r.GET("/getArticle", getArticle);
	r.POST("/createArticle", createArticle);
	r.POST("/likeArticle", likeArticle);
	r.POST("/testPost", testFunPost);
	r.POST("/testGet", testFunGet);




}


type ResultObj struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}


func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	dst := "./static/" + file.Filename
	err := c.SaveUploadedFile(file, dst)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":-1,
			"msg":err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":0,
		"data":file.Filename,
		"msg":"上传成功",
	})
}


func Cors() gin.HandlerFunc {
	return func(context *gin.Context) {
		method := context.Request.Method
		context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
		context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
		context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma,token,openid,opentoken,userId")
		context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
		context.Header("Access-Control-Max-Age", "172800")
		context.Header("Access-Control-Allow-Credentials", "false")
		context.Set("content-type", "application/json")

		if method == "OPTIONS" {
			context.JSON(http.StatusOK, nil)
		}
		//处理请求
		context.Next()
	}
}

